/*
 * pps_bom
 */
package com.pitop.product.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baidu.fsg.uid.UidGenerator;
import com.pitop.core.base.BaseDAO;
import com.pitop.core.base.BaseSVImpl;
import com.pitop.core.entity.Page;
import com.pitop.core.exceptions.BaseException;
import com.pitop.core.exceptions.ProductException;
import com.pitop.product.dao.ProductBomDAO;
import com.pitop.product.dao.ProductDAO;
import com.pitop.product.entity.Product;
import com.pitop.product.entity.ProductBom;
import com.pitop.product.entity.ProductState;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("productSV")
@Slf4j
public class ProductSVImpl extends BaseSVImpl<Product, Long> implements ProductSV {

    @Autowired
    private ProductDAO productDAO;

    @Autowired
    private ProductBomDAO productBomDAO;

    @Resource
    private UidGenerator uidGenerator;

    @Override
    protected BaseDAO getBaseDAO() {
        return productDAO;
    }

    /**
     * 保存account对象
     *
     * @param entity 实体
     * @throws BaseException
     */
    @Override
    public void save(Product entity) throws BaseException {
        if (entity == null) {
            throw new ProductException(BaseException.BaseExceptionEnum.Empty_Param);
        }
        if (StringUtils.isBlank(entity.getAlias())) {
            throw new ProductException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        if (StringUtils.isBlank(entity.getUpc())) {
            throw new ProductException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        if (StringUtils.isBlank(entity.getSku())) {
            throw new ProductException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        if (entity.getNum() == null) {
            throw new ProductException(BaseException.BaseExceptionEnum.Illegal_Param);
        }

        //检查别名，upc和sku是否存在
        Map<String, Object> params = new HashMap<>();
        params.put("alias", entity.getAlias());
        Product product = productDAO.load(params);
        if (product != null) {
            throw new ProductException(BaseException.BaseExceptionEnum.Exists);
        }
        params.clear();
        params.put("upc", entity.getUpc());
        product = productDAO.load(params);
        if (product != null) {
            throw new ProductException(BaseException.BaseExceptionEnum.Exists);
        }
        params.clear();
        params.put("sku", entity.getSku());
        product = productDAO.load(params);
        if (product != null) {
            throw new ProductException(BaseException.BaseExceptionEnum.Exists);
        }
        entity.setCode(String.valueOf(uidGenerator.getUID()));
        entity.setState(ProductState.Create.name());
        entity.setCreateTime(new Date());
        entity.setUpdateTime(new Date());
        entity.setVer(1);
        super.save(entity);
    }

    /**
     * 数据更新
     *
     * @param entity 实体
     * @throws BaseException
     */
    @Override
    public void modify(Product entity) throws BaseException {
        if (entity == null) {
            throw new ProductException(BaseException.BaseExceptionEnum.Empty_Param);
        }
//        if (entity.getId() == null) {
//            throw new ProductException(BaseException.BaseExceptionEnum.Illegal_Param);
//        }

        //检查别名，upc和sku是否存在
        Map<String, Object> params = new HashMap<>();
        Product product;
//        if (StringTools.isNotEmpty(entity.getAlias())) {
//            params.put("alias", entity.getAlias());
//             product = productDAO.load(params);
//            if (product != null) {
//                throw new ProductException(BaseException.BaseExceptionEnum.Exists);
//            }
//        }
//        if (StringTools.isNotEmpty(entity.getUpc())) {
//            params.clear();
//            params.put("upc", entity.getUpc());
//            product = productDAO.load(params);
//            if (product != null) {
//                throw new ProductException(BaseException.BaseExceptionEnum.Exists);
//            }
//        }
//
//        if (StringTools.isNotEmpty(entity.getSku())) {
//            params.clear();
//            params.put("sku", entity.getSku());
//            product = productDAO.load(params);
//            if (product != null) {
//                throw new ProductException(BaseException.BaseExceptionEnum.Exists);
//            }
//        }

        //检查要修改对象是否存在
        product = productDAO.loadByCode(entity.getCode());
        if (product == null) {
            throw new ProductException(BaseException.BaseExceptionEnum.Result_Not_Exist);
        }

        entity.setUpdateTime(new Date());
        productDAO.update(entity);
    }

    /**
     * 加载一个对象Product
     *
     * @param id
     * @param code 编码
     * @return Product
     */
    @Override
    public Product load(Long id, String code) {
        if (id == null && code == null) {
            throw new ProductException(BaseException.BaseExceptionEnum.Illegal_Param);
        }

        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        param.put("code", code);
        return productDAO.load(param);
    }

    /**
     * 加载一个对象Product,(将查询关联数据)
     *
     * @param id
     * @param code 编码
     * @return Product
     */
    @Override
    public Product get(Long id, String code) {
        if (id == null && code == null) {
            throw new ProductException(BaseException.BaseExceptionEnum.Illegal_Param);
        }

        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        param.put("code", code);
        return productDAO.getDetail(id, code);
    }

    /**
     * 加载一个对象Product 通过id
     *
     * @param id
     * @return Product
     */
    @Override
    public Product loadById(Long id) {
        if (id == null) {
            throw new ProductException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        return productDAO.loadById(id);
    }

    /**
     * 加载一个对象Product 通过code
     *
     * @param code 编码
     * @return Product
     */
    @Override
    public Product loadByCode(String code) {
        if (code == null) {
            throw new ProductException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        return productDAO.loadByCode(code);
    }

    /**
     * 加载一个对象Product 通过sku
     *
     * @param sku sku
     * @return Product
     */
    @Override
    public Product loadBySku(String sku) {
        return productDAO.loadBySku(sku);
    }

    /**
     * 加载一个对象Product 通过upc
     *
     * @param upc upc
     * @return Product
     */
    @Override
    public Product loadByUpc(String upc) {
        return productDAO.loadByUpc(upc);
    }

    /**
     * 加载一个对象Product 通过id,(将查询关联数据)
     *
     * @param id
     * @return Product
     */
    @Override
    public Product getById(Long id) {
        if (id == null) {
            throw new ProductException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        return productDAO.getById(id);
    }

    /**
     * 加载一个对象Product 通过code,(将查询关联数据)
     *
     * @param code 编码
     * @return Product
     */
    @Override
    public Product getByCode(String code) {
        if (code == null) {
            throw new ProductException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        return productDAO.getByCode(code);
    }

    /**
     * 根据主键id,oldStates 共同更新 Product 的状态到newState状态
     *
     * @param id
     * @param newState  新状态
     * @param oldStates 旧状态集合
     */
    @Override
    public void updateStateById(Long id, ProductState newState, ProductState... oldStates) {
        if (id == null) {
            throw new ProductException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        if (newState == null) {
            throw new ProductException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        if (oldStates == null) {
            throw new ProductException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        String[] states = new String[oldStates.length];
        for (int i = 0; i < oldStates.length; i++) {
            states[i] = oldStates[i].name();
        }
        productDAO.updateStateById(id, new Date(), newState.name(), states);
    }

    /**
     * 根据主键code,oldStates 共同更新 Product 的状态到newState状态
     *
     * @param code      编码
     * @param newState  新状态
     * @param oldStates 旧状态集合
     */
    @Override
    public void updateStateByCode(String code, ProductState newState, ProductState... oldStates) {
        if (code == null) {
            throw new ProductException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        if (newState == null) {
            throw new ProductException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        if (oldStates == null) {
            throw new ProductException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        String[] states = new String[oldStates.length];
        for (int i = 0; i < oldStates.length; i++) {
            states[i] = oldStates[i].name();
        }
        productDAO.updateStateByCode(code, new Date(), newState.name(), states);
    }

    /**
     * 根据主键id 更新 Product 的状态到另一个状态
     *
     * @param id
     * @param state 状态
     */
    @Override
    public void updateById(Long id, ProductState state) {
        if (id == null) {
            throw new ProductException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        productDAO.updateById(id, state.name(), new Date());
    }

    /**
     * 根据主键code 更新 Product 的状态到另一个状态
     *
     * @param code  编码
     * @param state 状态
     */
    @Override
    public void updateByCode(String code, ProductState state) {
        if (code == null) {
            throw new ProductException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        productDAO.updateByCode(code, state.name(), new Date());
    }


    /**
     * 删除对象Product
     *
     * @param id * @param code 编码
     * @return Product
     */
    @Override
    public void delete(Long id, String code) {
        if (id == null && code == null) {
            throw new ProductException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        param.put("code", code);
        productDAO.delete(param);
    }


    /**
     * 查询Product分页
     *
     * @param product 对象
     * @param offset  查询开始行
     * @param limit   查询行数
     * @return List<Product>
     */
    @Override
    public List<Product> list(Product product, int offset, int limit) {
        if (offset < 0) {
            offset = 0;
        }

        if (limit < 0) {
            limit = Page.limit;
        }

        Map<String, Object> map = null;
        if (product != null) {
            map = JSON.parseObject(JSON.toJSONString(product, SerializerFeature.WriteDateUseDateFormat));
        } else {
            map = new HashMap<>();
        }
        return productDAO.list(map, new RowBounds(offset, limit));
    }

    @Override
    public int count(Product product) {
        Map<String, Object> map = null;
        if (product != null) {
            map = JSON.parseObject(JSON.toJSONString(product, SerializerFeature.WriteDateUseDateFormat));
        } else {
            map = new HashMap<>();
        }
        return productDAO.count(map);
    }

    /**
     * 查询Product分页
     *
     * @param id     * @param code  编码
     * @param offset 查询开始行
     * @param limit  查询行数
     * @return List<Product>
     */
    @Override
    public List<Product> list(Long id, String code, int offset, int limit) {
        if (offset < 0) {
            offset = 0;
        }

        if (limit < 0) {
            limit = Page.limit;
        }
        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        param.put("code", code);
        return productDAO.list(param, new RowBounds(offset, limit));
    }

    @Override
    public int count(Long id, String code) {
        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        param.put("code", code);
        return productDAO.count(param);
    }

    /**
     * 复制成品
     *
     * @param code 成品编码
     */
    @Override
    public void copy(String code) {
        Product product = productDAO.getByCode(code);
        if (product == null) {
            throw new ProductException(BaseException.BaseExceptionEnum.Result_Not_Exist);
        }
        Product copyProduct = product;
        copyProduct.setId(null);
        copyProduct.setCode(String.valueOf(uidGenerator.getUID()));
        copyProduct.setAlias(product.getAlias() + "_copy");
        copyProduct.setSku(product.getSku() + "_copy");
        copyProduct.setUpc(product.getUpc() + "_copy");
        copyProduct.setCreateTime(new Date());
        copyProduct.setUpdateTime(new Date());
        productDAO.insert(copyProduct);
        //插入明细
        List<ProductBom> productBoms = product.getProductBomList();
        if (productBoms.size() > 0) {
            for (ProductBom productBom : productBoms) {
                productBom.setId(null);
                productBom.setProductCode(copyProduct.getCode());
                productBomDAO.insert(productBom);
            }
        }
    }

}
